package com.itheima.web.controller;

import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class BaseServlet extends HttpServlet {
    private ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        获取请求标记
//        获取serlvlet一级目录后的路径
        try {
            String pathInfo = req.getPathInfo().substring(1);
//        获取对应的方法Method对象
            Method method = this.getClass().getDeclaredMethod(pathInfo, HttpServletRequest.class, HttpServletResponse.class);
//        开启访问权限，暴力访问
            method.setAccessible(true);
//        反射执行方法
            Object result = method.invoke(this, req, resp);
            objectMapper.writeValue(resp.getOutputStream(),result);
        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}
